package com.cmc6.common.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cmc6.common.util.page.MyOrderItem;
import com.google.common.base.CaseFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
@ApiModel(description = "分页参数，查询所有：pageSize = -1，默认：pageNum = 1，pageSize = 10")
public class MyPage {

    @ApiModelProperty(value = "第几页")
    private long pageNum = 1;

    @ApiModelProperty(value = "每页显示条数")
    private long pageSize = 10;

    @ApiModelProperty(value = "排序字段信息")
    private List<MyOrderItem> orderList;

    @ApiModelProperty(value = "是否开启默认的排序规则（按照更新时间倒序）：true 是 false 否")
    private boolean defaultOrderFlag = false;

    /**
     * 分页属性拷贝
     */
    public <T> Page<T> getPage() {

        Page<T> target = new Page<>();

        target.setCurrent(getPageNum());
        target.setSize(getPageSize());
        if (CollUtil.isEmpty(orderList)) {
            if (defaultOrderFlag) {
                addDefaultOrder(target);
            }
            return target;
        }

        target.orders().addAll(orderListToOrders(orderList)); // 添加 orderList里面的排序规则
        if (defaultOrderFlag) {
            addDefaultOrder(target);
        }

        return target;
    }

    /**
     * 设置默认的排序规则
     */
    private <T> void addDefaultOrder(Page<T> target) {
        List<OrderItem> orders = target.orders();
        long count = orders.stream().filter(it -> it.getColumn().contains("update_time")).count();
        if (count == 0) {
            // 如果没有根据更新时间进行排序，那么默认添加一个根据更新时间排序（倒序：最近更新的在前面）
            OrderItem orderItem = new OrderItem();
            orderItem.setColumn("update_time");
            orderItem.setAsc(false);
            orders.add(orderItem);
        }
    }

    /**
     * 自定义的排序规则，转换为 mybatis plus 的排序规则
     */
    public static List<OrderItem> orderListToOrders(List<MyOrderItem> orderList) {
        List<OrderItem> orders = new ArrayList<>();
        for (MyOrderItem item : orderList) {
            if (StrUtil.isBlank(item.getName())) {
                continue;
            }
            if (item.getType() == null || 1 == item.getType()) {
                item.setName(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, item.getName()));
            }
            OrderItem orderItem = new OrderItem();
            orderItem.setColumn(item.getName());
            if (StrUtil.isNotBlank(item.getValue())) {
                orderItem.setAsc("ascend".equalsIgnoreCase(item.getValue()));
            }
            orders.add(orderItem);
        }
        return orders;
    }

}
